package br.com.social.mobile.servlet;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.social.mobile.dao.ParameterDAO;
import br.com.social.mobile.entities.Parameter;
import br.com.social.mobile.entities.Profile;
import br.com.social.mobile.util.IConstants;

public class ImageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		String img = request.getParameter("img");
		String defaultImage = "default_marker.png";
		
		Profile profile = (Profile) session.getAttribute(Profile.class
				.getName());

		if (profile == null) {
			img = defaultImage;
		}		
		
		response.setContentType("image/jpeg");
		String path = "";
		
		if (session.getAttribute(IConstants.PARAMETER.PATH_SAVE_IMAGE) == null) {
			ParameterDAO dao = new ParameterDAO();
			Parameter parameter = dao.findByParamName(IConstants.PARAMETER.PATH_SAVE_IMAGE);
			path = parameter.getDsParamValue();
			session.setAttribute(IConstants.PARAMETER.PATH_SAVE_IMAGE, path);
		} else {
			path = (String) session.getAttribute(IConstants.PARAMETER.PATH_SAVE_IMAGE);
		}
		
	
		String pathToWeb = path + img ;
		try {
			

			File f = new File(pathToWeb);
			BufferedImage bi = ImageIO.read(f);
			OutputStream out = response.getOutputStream();
			ImageIO.write(bi, "png", out);
			out.close();
		
		} catch (Exception e) {
			pathToWeb = path + defaultImage;
			File f = new File(pathToWeb);
			BufferedImage bi = ImageIO.read(f);
			OutputStream out = response.getOutputStream();
			ImageIO.write(bi, "png", out);
			out.close();
		}

	}

}